package com.danawa.mds.market.model;

import org.springframework.beans.factory.annotation.Configurable;

@Configurable(value="orderLineItem",preConstruction=true)
public class OrderLineItem {
	private Long id;
	private int quantity;
	private Goods goods;

	private GoodsRepository goodsRepository;
	
	public OrderLineItem() {
	}
	
	public OrderLineItem(Long goodsId, int quantity) {
		this.goods = goodsRepository.find(goodsId);
		this.quantity = quantity;
	}

	public void setGoodsRepository(GoodsRepository goodsRepository) {
		this.goodsRepository = goodsRepository;
	}
	
	public Money getPrice() {
		return goods.getPrice().multiply(quantity);
	}

	public boolean isGoodsEqual(OrderLineItem lineItem) {
		return goods == lineItem.goods;
	}

	public OrderLineItem merge(OrderLineItem lineItem) {
		quantity += lineItem.quantity;
		return this;
	}

	int getQuantity() {
		return quantity;
	}

	@Override
	public int hashCode() {
		int result = 17;
		result = 37 * result + goods.hashCode();
		result = 37 * result + quantity;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == this) {
			return true;
		}
		
		if (!(obj instanceof OrderLineItem)) {
			return false;
		}
		
		final OrderLineItem other = (OrderLineItem) obj;
		return this.goods.equals(other.getGoods()) &&
				this.quantity == other.getQuantity();
	}

	Goods getGoods() {
		return goods;
	}

}
